<template>
    <div class="layout-page">
        <Layout class="layout-div">
            <Sider ref="side1" hide-trigger collapsible :collapsed-width="78" :width="200"
                   :class="themeType==='light'?'themeLight':'themeDark'" v-model="isCollapsed">
                <div class="logo" :class="headMaxWidth?'headMaxWidth':''">
                    <img v-if="!isCollapsed && headMaxWidth" :src="headMaxWidthLogoImg" alt="">
                    <img v-if="!isCollapsed && !headMaxWidth" :src="logoImg" alt="">
                    <img v-if="isCollapsed" src="../../assets/main/logo-small.png" alt="">
                </div>
                <Menu :active-name="activeName" :open-names="openNames" :class="menuitemClasses" :theme="themeType" @on-select="menuNav" @on-open-change="open" width="auto" ref="side_menu" accordion>
                    <template v-if="!isCollapsed">
                        <template v-for="(item,index) in menusData">
                            <Submenu v-if="item.children" :name="item.name" :key="index">
                                <template slot="title">
                                    <Icon :type="item.icon"/>
                                    <span class="title-span">{{item.title}}</span>
                                </template>
                                <template v-for="it in item.children">
                                    <MenuItem v-if="!it.children" :key="it.name" :name="it.name">
                                        <Icon :type="it.icon"/>
                                        <span>{{it.title}}</span>
                                    </MenuItem>
                                    <Submenu v-else :name="it.name" :key="it.name">
                                        <template slot="title">
                                            <span class="title-span">{{it.title}}</span>
                                        </template>
                                        <MenuItem v-for="i in it.children" :key="i.name" :name="i.name">
                                            <span>{{i.title}}</span>
                                        </MenuItem>
                                    </Submenu>
                                </template>
                            </Submenu>
                            <template v-else>
                                <!--如果只有一个子路由-->
                                <MenuItem :key="item.name" class="ivu-menu-submenu" :class="{ 'liActive': $route.name === item.name}" style="padding: 0!important;" :name="item.name">
                                    <div class="ivu-menu-submenu-title">
                                        <Icon :type="item.icon"/>
                                        <span style="margin-left: 10px">{{item.title}}</span>
                                    </div>
                                </MenuItem>
                            </template>
                        </template>
                    </template>
                    <template v-else>
                        <template v-for="(item,index) in menusData">
                            <Dropdown :key="index" v-if="item.children" class="menuSmall" @on-click="dropdownNav">
                            <span :class="item.name === $route.meta.fuName?'active':''">
                                <Icon :type="item.icon"/>
                            </span>
                                <DropdownMenu slot="list">
                                    <template v-for="it in item.children">
                                        <DropdownItem :key="it.name" :name="it.name" :selected="it.name === activeName">{{it.title}}
                                        </DropdownItem>
                                    </template>
                                </DropdownMenu>
                            </Dropdown>
                            <template v-else>
                                <Tooltip class="menuSmall" :key="item.name" :content="item.title" placement="right">
                                    <MenuItem :class="{ 'active': $route.name === item.name}" style="padding: 0!important;"
                                              :name="item.name">
                                        <span>
                                           <Icon :type="item.icon"/>
                                        </span>
                                    </MenuItem>
                                </Tooltip>
                            </template>
                        </template>
                    </template>
                </Menu>
            </Sider>
            <Layout>
                <Header class="header flexR">
                    <div class="header_left flexR">
                        <span class="header-trigger">
                            <Icon @click.native="collapsedSider" :class="rotateIcon" custom="i-icon" size="20"></Icon>
                        </span>
                        <span @click="refresh()" class="header-trigger" >
                            <Icon type="md-refresh" size="20"/>
                        </span>
                        <span>
                            <Breadcrumb>
                            <BreadcrumbItem>首页</BreadcrumbItem>
                            <BreadcrumbItem>{{$route.meta.fuTitle}}</BreadcrumbItem>
                            <BreadcrumbItem v-if="$route.meta.title !== $route.meta.fuTitle">{{$route.meta.title}}</BreadcrumbItem>
                        </Breadcrumb>
                        </span>
                    </div>
                    <!--头部右边-->
                    <div class="header_right flexR">
                        <span>
                            <Input placeholder="搜索..."  style="width: 200px;outline: none;border: none;color: inherit;background: transparent;" />
                        </span>
                        <span class="header-trigger"  @click="fullscreen">
                            <Icon custom="i-icon" :class="fullscreenIcon" size="20"/>
                        </span>
                        <span class="header-trigger">
                            <Dropdown trigger="click">
                                <Badge :count="3">
                                    <Icon type="ios-notifications-outline" size="20"/>
                                </Badge>
                                <DropdownMenu slot="list">
                                    <message/>
                                </DropdownMenu>
                            </Dropdown>
                       </span>
                        <span class="header-trigger">
                            <Dropdown @on-click="personalSettings">
                              <a href="javascript:void(0)" style="color: #515A6E;">
                                  <img :src="FileBaseURL+$store.getters.userData.icon_url" alt=""
                                       class="ivu-avatar ivu-avatar-small"
                                       style="margin-right: 5px">
                                 {{$store.getters.userData.userName}}
                              </a>
                              <DropdownMenu slot="list" style="text-align: left;">
                                  <DropdownItem name="personal"><Icon type="ios-contact-outline"  size="20" />个人中心</DropdownItem>
                                  <DropdownItem><Icon type="ios-settings-outline" size="20" />设置</DropdownItem>
                                  <DropdownItem divided name="logout"><Icon type="ios-log-out"  size="20" />退出登录</DropdownItem>
                              </DropdownMenu>
                            </Dropdown>
                        </span>
                        <span @click="optionDrawer = true" class="header-trigger">
                           <Icon type="md-more" size="20"/>
                        </span>
                    </div>
                </Header>

                <!--多页标签-->
                <div v-if="isTabsShow" class="tabsNav flexR">
                    <div class="dropDown pointer" v-if="tabSwitch" @click="tabLeft">
                        <Icon type="ios-arrow-back" size="16"/>
                    </div>
                    <div class="left flexR" id="tabsNav">
                        <div class="flexR" id="tabsDiv" :style="{transform:transform}">
                            <div class="pointer flexR" v-for="(item,index) in $store.getters.routerArr" :key="item+index">
                                <span :class="activeName === item.name?'active':''" @click="tabNav(item.name)" >{{item.meta.title}}</span>
                                <Icon  v-if="item.name !== $indexPage" type="ios-close" size="22" @click="tabNavClose(item,index)"/>
                            </div>
                        </div>
                    </div>
                    <div class="dropDown pointer" v-if="tabSwitch" @click="tabRight">
                        <Icon type="ios-arrow-forward" size="16"/>
                    </div>
                    <div class="right">
                        <Dropdown style="margin-left: 5px;" @on-click="tabRightClick">
                            <div class="dropDown pointer">
                                <Icon type="ios-arrow-down"/>
                            </div>
                            <DropdownMenu slot="list">
                                <DropdownItem name="qt">关闭其他</DropdownItem>
                                <DropdownItem name="qb">全部关闭</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </div>
                </div>
                <Content id="main_content"
                         :style="{height: (!isTabsShow?'calc(100vh - 64px)':'calc(100vh - 108px)'), margin: (!isTabsShow ? '0 15px 0 15px':'0 15px 0 15px') }"
                         class="main_content flexC">
                    <router-view v-if="isRouterViewShow"></router-view>
                    <Footer></Footer>
                </Content>
                <Drawer v-model="optionDrawer" class="optionDrawer">
                    <Divider slot="header" class="header">主题风格设置</Divider>
                    <div class="flexR images">
                        <Tooltip content="时尚酷黑" placement="top" transfer :class="themeType === 'dark'?'active':''">
                            <img src="../../assets/main/nav-theme-dark.svg" alt="" @click="themeSwitch(0)">
                        </Tooltip>
                        <Tooltip content="极简雅白" placement="top" transfer :class="themeType === 'light'?'active':''">
                            <img src="../../assets/main/nav-theme-light.svg" alt="" @click="themeSwitch(1)">
                        </Tooltip>
                    </div>
                    <Divider class="otherDiv">其他设置</Divider>
                    <div class="switch flexR">
                        <span>开启多页签</span>
                        <i-switch v-model="isTabsShow" size="small"/>
                    </div>
                    <div class="switch flexR">
                        <span>顶栏通顶</span>
                        <i-switch v-model="headMaxWidth" size="small"/>
                    </div>
                </Drawer>
            </Layout>
        </Layout>
    </div>
</template>
<script>
import screenFull from 'screenfull'
import Footer from '@/components/footer/footer'
import message from "@/components/message/message"
import {clientId, themeData} from '@/config/config'
import darkImg from '@/assets/main/logo-dark.png'
import lightImg from '@/assets/main/logo-light.png'
import {getMenu} from '@/api/menuApi'
export default {
  components: {message,Footer},
  data() {
    return {
      isCollapsed: false,
      isFullscreen: false,
      messageVisible: false,
      optionDrawer: false,
      isTabsShow: themeData.isTabsShow, // 是否显示多页签
      activeName: '',
      openNames: [],
      transform: 0, // 导航左右方向移动距离
      tabSwitch: false, // 是否显示左右切换图标
      themeType: themeData.themeType,
      logoImg: themeData.themeType === 'dark' ? lightImg : darkImg, // 主题logo图片
      headMaxWidthLogoImg: darkImg, // 栏目是否通顶logo图片
      headMaxWidth: themeData.headMaxWidth, // 栏目是否通顶（最大宽度）
      menusData: [],
      isRouterViewShow: true, // 控制router-view的隐藏与展示
      FileBaseURL:"file/",
    }
  },
  created() {
    this.initMenusData()
  },
  mounted: function () {
    if (screenFull.isEnabled) {
      screenFull.on('change', this.fullChange)
    }
    if (this.$route.meta.hide) {
      this.$router.push({
            name: this.$indexPage
          }
      )
    }
            // 页面刷新后 保存打开的路由数据到本地存储
    window.addEventListener('unload', this.saveState)
    this.activeName = this.$route.name
    this.openNames = []
    this.openNames.push(this.$route.meta.fuName)
    this.$nextTick(() => {
      // 重新渲染导航
      if (this.$refs.side_menu) {
        this.$refs.side_menu.updateOpened()
      }
    })
  },
  watch: {
            // 监听路由跳转
    $route() {
      this.activeName = this.$route.name
      this.openNames = []
      this.openNames.push(this.$route.meta.fuName)
      this.$nextTick(() => {
        this.$refs.side_menu.updateOpened()
        this.$refs.side_menu.updateActiveName()
        this.saveState()
      })
    },
    // 监听路由数组改变
    getRouterArrVuex(val) {
      if (val.length < 1) {
        this.$router.push({name: this.$indexPage})
      }
      // 动态监听路由变化 自动滚动多页签导航
      this.$nextTick(()=>{
        // 修复退出登录 页面报错
        if(document.getElementById('tabsNav')) {
          let zw = document.getElementById('tabsNav').offsetWidth // 总宽度
          let w = document.getElementById('tabsDiv').offsetWidth // 导航宽度
          if (w > zw) {
            let s = -(w - zw)
            this.transform = 'translateX(' + s + 'px)'
          } else {
            this.tabLeft()
          }
        }
      })
    }
  },
  computed: {
    rotateIcon() {
      return [this.isCollapsed ? 'i-icon-menu-unfold' : 'i-icon-menu-fold'];
    },
    fullscreenIcon() {
      return [this.isFullscreen ? 'i-icon-exit-full-screen' : 'i-icon-full-screen']},
            // 导航收缩
    menuitemClasses() {
      return [
        'menu-item',
        this.isCollapsed ? 'collapsed-menu' : ''
      ]
    }
  },
  methods: {
            // 收缩切换
    collapsedSider() {
      this.$refs.side1.toggleCollapse();
      this.$nextTick(() => {
        // 重新渲染导航
        this.$refs.side_menu.updateOpened()
        this.$refs.side_menu.updateActiveName()
      })
    },
    fullscreen() {
      this.isFullscreen = !this.isFullscreen;
      // 全屏切换
      screenFull.toggle();
    },
            // 路由跳转
    routerPush(name) {
      this.$router.push({
        name: name
      })
      this.$nextTick(() => {
        let w = document.getElementById('tabsDiv').offsetWidth
        let zw = document.getElementById('tabsNav').offsetWidth
        if (w > zw) {
          this.tabSwitch = true
        }
      })
    },
            // 导航跳转
    menuNav(name) {
      // this.activeName = name
      this.routerPush(name)
    },
    // 下拉菜单跳转
    dropdownNav(name) {
      this.routerPush(name)
    },
    // tab切换跳转
    tabNav(name) {
      this.routerPush(name)
    },
            // 父级栏目展开收缩事件
    open(name) {
      this.openNames = ['' + name + '']
    },
    // 页面刷新后 将vuex路由数据存储到本地
    saveState() {
      let arr = this.$store.getters.routerArr
      let arr1 = []
      for (let v of arr) {
        let item = {
          fullPath: v.fullPath,
          meta: v.meta,
          name: v.name,
          path: v.path
        }
        arr1.push(item)
      }
      localStorage.setItem('dataRouter', JSON.stringify(arr1))
    },
    // 页面刷新
    refresh() {
                // 先隐藏
      this.isRouterViewShow = false
                // $nextTick() 将回调延迟到下次 DOM 更新循环之后执行
      this.$nextTick(() => {
        this.isRouterViewShow = true
      })
    },
            // 向左切换
    tabLeft() {
      this.transform = 'translateX(0px)'
    },
            // 向右切换
    tabRight() {
      let w = document.getElementById('tabsDiv').offsetWidth
      let zw = document.getElementById('tabsNav').offsetWidth
      if (w > zw) {
        let s = -(w - zw)
          this.transform = 'translateX(' + s + 'px)'
      }
    },
    // tab关闭
    tabNavClose(item, index) {
      console.log('tabNavClose')
      let arr = this.$store.getters.routerArr
      // 判断是否是首页
      if (item.name !== this.$indexPage) {
        this.$store.dispatch('tagsView/delRouter', index)
        if (index !== 0) {
          this.$router.push({name: arr[index - 1].name})
        }
      }
      this.$nextTick(() => {
        let w = document.getElementById('tabsDiv').offsetWidth
        let zw = document.getElementById('tabsNav').offsetWidth
        if (w < zw) {
          this.tabSwitch = false
        }
      })
    },
            // tab最右侧下拉框右键选中
    tabRightClick(type) {
      let arr = this.$store.getters.routerArr
      this.tabSwitch = false
      switch (type) {
        case 'qt':
          for (let i = arr.length - 1; i > -1; i--) {
            if (arr[i].name !== this.activeName) {
              this.$store.dispatch('tagsView/delRouter', i)
            }
          }
          break
        case 'qb':
          if(arr.length === 1) {
            if(this.$route.name !== this.$indexPage) {
              for (let i = arr.length - 1; i > -1; i--) {
                this.$store.dispatch('tagsView/delRouter', i)
              }
            }
          } else {
            for (let i = arr.length - 1; i > -1; i--) {
              this.$store.dispatch('tagsView/delRouter', i)
            }
          }
          break
      }
    },
            // 主题切换
    themeSwitch(type) {
      if (type === 0) {
        this.themeType = 'dark'
        this.logoImg = lightImg
      } else {
        this.themeType = 'light'
        this.logoImg = darkImg
      }
    },
    initMenusData () {
      let storeMenuList = sessionStorage.getItem('menusList')
      if (storeMenuList){
        this.menusData = JSON.parse(storeMenuList)
      }else{
        getMenu().then(res =>{
          this.menusData = res
          sessionStorage.setItem('menusList', JSON.stringify(res))
        })
      }
    },
    // 个人设置功能
    personalSettings (name) {
      if (name === 'logout') {
        sessionStorage.clear();
        this.$store.dispatch('user/logout')
        this.$router.push({name: this.$loginPage, query: { clientId: clientId }})
      }else if (name === 'personal'){
        this.$router.push({name: 'personal',})
      }
    },
    fullChange() {
      this.isFullscreen = screenFull.isFullscreen
    },
  }
}
</script>
<style lang="less">
@import "main";
</style>